<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>天气应用</title>
  <!-- 引入Vue3 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <!-- Tailwind配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#1E40AF', // 深蓝色主色调
            secondary: '#3B82F6', // 浅蓝色辅助色
            accent: '#0EA5E9', // 亮蓝色强调色
            dark: '#0F172A', // 深色模式背景
            light: '#F8FAFC', // 浅色模式背景
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <!-- 配置自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .weather-card {
        @apply bg-white dark:bg-dark rounded-xl shadow-lg transition-all duration-300;
      }
      .weather-card:hover {
        @apply shadow-xl transform scale-[1.02];
      }
      /* 其他工具类定义 */
    }
  </style>
  <!-- 确保Tailwind处理所有样式 -->
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
    
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 dark:bg-gray-900 min-h-screen flex flex-col transition-colors duration-300">
  <div id="app" class="flex-grow container mx-auto px-4 py-8">
    <!-- 顶部导航栏 -->
    <header class="mb-8">
      <div class="flex flex-col md:flex-row md:items-center justify-between">
        <div class="flex items-center mb-4 md:mb-0">
          <i class="fa fa-cloud text-primary text-3xl mr-3"></i>
          <h1 class="text-2xl md:text-3xl font-bold text-neutral-800 dark:text-white">天气应用</h1>
        </div>
        <div class="flex items-center space-x-4">
          <div class="relative">
            <input 
              type="text" 
              v-model="searchQuery" 
              placeholder="搜索城市..." 
              class="input-primary pl-10 w-full md:w-64"
            >
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>
          <button @click="searchCity" class="btn-primary">
            <i class="fa fa-search mr-2"></i>搜索
          </button>
          <button @click="toggleDarkMode" class="btn-secondary">
            <i class="fa fa-moon-o dark:hidden"></i>
            <i class="fa fa-sun-o hidden dark:inline"></i>
          </button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow">
      <!-- 当前位置和日期 -->
      <div class="mb-6">
        <h2 class="text-xl md:text-2xl font-semibold text-neutral-800 dark:text-white">
          {{ currentLocation }}
          <span class="text-sm md:text-base font-normal text-neutral-500 dark:text-neutral-400 ml-2">
            {{ currentDate }}
          </span>
        </h2>
      </div>

      <!-- 主要天气信息 -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        <!-- 当前天气卡片 -->
        <div class="lg:col-span-2 weather-card p-6 animate-fade-in">
          <div class="flex flex-col md:flex-row md:items-center justify-between">
            <div class="mb-6 md:mb-0">
              <div class="flex items-center mb-3">
                <img :src="getWeatherIcon(currentWeather.condition.code)" alt="天气图标" class="weather-icon">
                <div class="ml-4">
                  <h3 class="text-xl font-semibold text-neutral-800 dark:text-white">{{ currentWeather.condition.text }}</h3>
                  <p class="text-neutral-500 dark:text-neutral-400">体感温度: {{ currentWeather.feelslike_c }}°C</p>
                </div>
              </div>
              <div class="temperature-big text-neutral-800 dark:text-white">
                {{ currentWeather.temp_c }}°<span class="text-xl font-normal">C</span>
              </div>
              <div class="mt-2 text-neutral-600 dark:text-neutral-300">
                <i class="fa fa-tint mr-1"></i>湿度: {{ currentWeather.humidity }}%
                <span class="mx-3">•</span>
                <i class="fa fa-wind mr-1"></i>风速: {{ currentWeather.wind_kph }} km/h
              </div>
            </div>
            <div class="w-full md:w-px h-32 md:h-48 bg-gray-200 dark:bg-gray-700 mx-4 hidden md:block"></div>
            <div class="w-full md:w-auto">
              <h4 class="text-lg font-semibold text-neutral-800 dark:text-white mb-4">今日详情</h4>
              <div class="space-y-3">
                <div class="weather-details-item">
                  <span class="text-neutral-600 dark:text-neutral-400">最高温度</span>
                  <span class="font-medium text-neutral-800 dark:text-white">{{ forecast.forecastday[0].day.maxtemp_c }}°C</span>
                </div>
                <div class="weather-details-item">
                  <span class="text-neutral-600 dark:text-neutral-400">最低温度</span>
                  <span class="font-medium text-neutral-800 dark:text-white">{{ forecast.forecastday[0].day.mintemp_c }}°C</span>
                </div>
                <div class="weather-details-item">
                  <span class="text-neutral-600 dark:text-neutral-400">日出时间</span>
                  <span class="font-medium text-neutral-800 dark:text-white">{{ forecast.forecastday[0].astro.sunrise }}</span>
                </div>
                <div class="weather-details-item">
                  <span class="text-neutral-600 dark:text-neutral-400">日落时间</span>
                  <span class="font-medium text-neutral-800 dark:text-white">{{ forecast.forecastday[0].astro.sunset }}</span>
                </div>
                <div class="weather-details-item">
                  <span class="text-neutral-600 dark:text-neutral-400">降水概率</span>
                  <span class="font-medium text-neutral-800 dark:text-white">{{ forecast.forecastday[0].day.daily_chance_of_rain }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 快速操作卡片 -->
        <div class="weather-card p-6 animate-fade-in" style="animation-delay: 0.1s">
          <h3 class="text-lg font-semibold text-neutral-800 dark:text-white mb-4">快速操作</h3>
          <div class="space-y-4">
            <button @click="getMyLocation" class="btn-primary w-full flex items-center justify-center">
              <i class="fa fa-map-marker mr-2"></i>定位当前位置
            </button>
            <button @click="toggleTemperatureUnit" class="btn-secondary w-full flex items-center justify-center">
              <i class="fa fa-exchange mr-2"></i>切换温度单位 ({{ temperatureUnit === 'c' ? '°C' : '°F' }})
            </button>
            <button @click="refreshWeather" class="btn-secondary w-full flex items-center justify-center">
              <i class="fa fa-refresh mr-2"></i>刷新天气数据
            </button>
            <div class="pt-2">
              <p class="text-sm text-neutral-500 dark:text-neutral-400 text-center">
                数据更新于: {{ lastUpdated }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 5天天气预报 -->
      <div class="mb-8 animate-fade-in" style="animation-delay: 0.2s">
        <h3 class="text-xl font-semibold text-neutral-800 dark:text-white mb-4">5天天气预报</h3>
        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div v-for="(day, index) in forecast.forecastday.slice(1)" :key="index" class="day-card">
            <p class="font-medium text-neutral-800 dark:text-white mb-2">{{ getWeekday(day.date) }}</p>
            <img :src="getWeatherIcon(day.day.condition.code)" alt="天气图标" class="weather-icon mb-3">
            <p class="temperature-small text-neutral-800 dark:text-white">
              {{ day.day.maxtemp_c }}° / {{ day.day.mintemp_c }}°
            </p>
            <p class="text-sm text-neutral-600 dark:text-neutral-400 mt-2">
              {{ day.day.condition.text }}
            </p>
          </div>
        </div>
      </div>

      <!-- 每小时天气预报 -->
      <div class="mb-8 animate-fade-in" style="animation-delay: 0.3s">
        <h3 class="text-xl font-semibold text-neutral-800 dark:text-white mb-4">今日每小时预报</h3>
        <div class="overflow-x-auto">
          <div class="flex space-x-4 pb-4 min-w-max">
            <div v-for="(hour, index) in forecast.forecastday[0].hour.slice(now.getHours(), now.getHours() + 12)" :key="index" class="day-card min-w-[80px]">
              <p class="font-medium text-neutral-800 dark:text-white mb-2">{{ getHour(hour.time) }}</p>
              <img :src="getWeatherIcon(hour.condition.code)" alt="天气图标" class="weather-icon mb-2 w-12 h-12">
              <p class="temperature-small text-neutral-800 dark:text-white">
                {{ hour.temp_c }}°
              </p>
              <p class="text-xs text-neutral-600 dark:text-neutral-400 mt-1">
                {{ hour.chance_of_rain }}%
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 最近搜索城市 -->
      <div class="animate-fade-in" style="animation-delay: 0.4s">
        <h3 class="text-xl font-semibold text-neutral-800 dark:text-white mb-4">最近搜索</h3>
        <div class="flex flex-wrap gap-3">
          <button 
            v-for="(city, index) in recentSearches" 
            :key="index" 
            @click="loadSavedCity(city)"
            class="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-all duration-200"
          >
            {{ city.name }}
            <span class="ml-1 text-sm text-neutral-500 dark:text-neutral-400">
              {{ city.temp_c }}°C
            </span>
          </button>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="mt-12 text-center text-neutral-500 dark:text-neutral-400 text-sm py-4">
      <p>© 2023 天气应用 | 数据来源: 示例API</p>
      <p class="mt-1">本应用仅供演示，实际使用请替换为真实API</p>
    </footer>
  </div>

  <script>
    // 天气图标映射表
    const weatherIcons = {
      // 晴天
      1000: 'https://picsum.photos/id/1000/100/100',
      // 多云
      1003: 'https://picsum.photos/id/1003/100/100',
      1006: 'https://picsum.photos/id/1006/100/100',
      1009: 'https://picsum.photos/id/1009/100/100',
      // 雨
      1063: 'https://picsum.photos/id/1063/100/100',
      1180: 'https://picsum.photos/id/1180/100/100',
      1183: 'https://picsum.photos/id/1183/100/100',
      1186: 'https://picsum.photos/id/1186/100/100',
      1189: 'https://picsum.photos/id/1189/100/100',
      1192: 'https://picsum.photos/id/1192/100/100',
      1195: 'https://picsum.photos/id/1195/100/100',
      // 雪
      1066: 'https://picsum.photos/id/1066/100/100',
      1114: 'https://picsum.photos/id/1114/100/100',
      1117: 'https://picsum.photos/id/1117/100/100',
      1210: 'https://picsum.photos/id/1210/100/100',
      1213: 'https://picsum.photos/id/1213/100/100',
      1216: 'https://picsum.photos/id/1216/100/100',
      1219: 'https://picsum.photos/id/1219/100/100',
      1222: 'https://picsum.photos/id/1222/100/100',
      1225: 'https://picsum.photos/id/1225/100/100',
      // 雷暴
      1087: 'https://picsum.photos/id/1087/100/100',
      1273: 'https://picsum.photos/id/1273/100/100',
      1276: 'https://picsum.photos/id/1276/100/100',
      1279: 'https://picsum.photos/id/1279/100/100',
      1282: 'https://picsum.photos/id/1282/100/100',
      // 默认图标
      default: 'https://picsum.photos/id/1015/100/100'
    };

    const { createApp } = Vue;
    const app = createApp({
      data() {
        return {
          currentLocation: '北京市',
          currentWeather: {},
          forecast: {},
          searchQuery: '',
          temperatureUnit: 'c', // 'c' 或 'f'
          recentSearches: [],
          now: new Date(),
          lastUpdated: '',
          isDarkMode: false
        };
      },
      computed: {
        currentDate() {
          const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
          return this.now.toLocaleDateString('zh-CN', options);
        }
      },
      methods: {
        // 获取天气图标
        getWeatherIcon(code) {
          return weatherIcons[code] || weatherIcons.default;
        },
        
        // 获取星期几
        getWeekday(dateString) {
          const date = new Date(dateString);
          const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
          return weekdays[date.getDay()];
        },
        
        // 获取小时
        getHour(timeString) {
          const date = new Date(timeString);
          return date.getHours() + ':00';
        },
        
        // 搜索城市天气
        searchCity() {
          if (!this.searchQuery.trim()) return;
          
          // 这里应该调用实际的API
          this.fetchWeatherData(this.searchQuery);
          this.searchQuery = '';
        },
        
        // 获取当前位置天气
        getMyLocation() {
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              position => {
                const { latitude, longitude } = position.coords;
                // 这里应该调用实际的API
                this.fetchWeatherData(`${latitude},${longitude}`);
              },
              error => {
                alert('无法获取位置信息，请手动搜索城市');
                console.error('Geolocation error:', error);
              }
            );
          } else {
            alert('您的浏览器不支持地理位置服务，请手动搜索城市');
          }
        },
        
        // 切换温度单位
        toggleTemperatureUnit() {
          this.temperatureUnit = this.temperatureUnit === 'c' ? 'f' : 'c';
          // 更新最近搜索的城市温度显示
          this.recentSearches.forEach(city => {
            city.temp_c = this.convertTemperature(city.temp_c);
          });
        },
        
        // 转换温度单位
        convertTemperature(temp) {
          if (this.temperatureUnit === 'c') {
            // 从华氏转摄氏
            return Math.round((temp - 32) * 5 / 9);
          } else {
            // 从摄氏转华氏
            return Math.round(temp * 9 / 5 + 32);
          }
        },
        
        // 刷新天气数据
        refreshWeather() {
          this.fetchWeatherData(this.currentLocation);
        },
        
        // 加载已保存的城市
        loadSavedCity(city) {
          this.fetchWeatherData(city.name);
        },
        
        // 切换深色模式
        toggleDarkMode() {
          this.isDarkMode = !this.isDarkMode;
          document.documentElement.classList.toggle('dark', this.isDarkMode);
        },
        
        // 模拟获取天气数据
        fetchWeatherData(location) {
          // 这里应该是实际的API调用
          // 为了演示，我们使用模拟数据
          
          // 更新最后更新时间
          this.lastUpdated = new Date().toLocaleTimeString('zh-CN');
          
          // 模拟API响应延迟
          setTimeout(() => {
            // 模拟API数据
            const mockData = this.getMockWeatherData(location);
            
            // 更新数据
            this.currentLocation = mockData.location.name;
            this.currentWeather = mockData.current;
            this.forecast = mockData.forecast;
            
            // 添加到最近搜索
            this.addToRecentSearches({
              name: mockData.location.name,
              temp_c: mockData.current.temp_c
            });
            
            // 更新当前时间
            this.now = new Date();
            
            // 显示成功消息
            this.showNotification(`已更新 ${mockData.location.name} 的天气数据`);
          }, 800);
        },
        
        // 添加到最近搜索
        addToRecentSearches(city) {
          // 检查是否已存在
          const index = this.recentSearches.findIndex(item => item.name === city.name);
          
          if (index !== -1) {
            // 如果已存在，移除它
            this.recentSearches.splice(index, 1);
          }
          
          // 添加到开头
          this.recentSearches.unshift(city);
          
          // 限制最多保存5个
          if (this.recentSearches.length > 5) {
            this.recentSearches.pop();
          }
        },
        
        // 显示通知
        showNotification(message) {
          // 实际项目中可以使用更高级的通知组件
          alert(message);
        },
        
        // 获取模拟天气数据
        getMockWeatherData(location) {
          // 为不同城市生成不同的天气数据
          const baseTemp = location.includes('北京') ? 22 : 
                          location.includes('上海') ? 25 : 
                          location.includes('广州') ? 28 : 
                          location.includes('哈尔滨') ? 18 : 
                          location.includes('三亚') ? 30 : 24;
                          
          const conditions = [
            { code: 1000, text: '晴朗' },
            { code: 1003, text: '多云' },
            { code: 1063, text: '小雨' },
            { code: 1087, text: '雷阵雨' },
            { code: 1183, text: '中雨' }
          ];
          
          const randomCondition = conditions[Math.floor(Math.random() * conditions.length)];
          
          return {
            location: {
              name: location.includes(',') ? '当前位置' : location,
              region: '示例地区',
              country: '中国',
              localtime: new Date().toISOString()
            },
            current: {
              last_updated: new Date().toISOString(),
              temp_c: baseTemp + Math.floor(Math.random() * 5) - 2,
              temp_f: Math.round(baseTemp * 9 / 5 + 32),
              feelslike_c: baseTemp + Math.floor(Math.random() * 3) - 1,
              feelslike_f: Math.round((baseTemp + Math.floor(Math.random() * 3) - 1) * 9 / 5 + 32),
              condition: randomCondition,
              wind_kph: Math.floor(Math.random() * 20) + 5,
              humidity: Math.floor(Math.random() * 40) + 40
            },
            forecast: {
              forecastday: [
                {
                  date: new Date().toISOString().split('T')[0],
                  day: {
                    maxtemp_c: baseTemp + 3,
                    mintemp_c: baseTemp - 3,
                    condition: randomCondition,
                    daily_chance_of_rain: Math.floor(Math.random() * 60)
                  },
                  astro: {
                    sunrise: '06:00 AM',
                    sunset: '07:30 PM'
                  },
                  hour: Array.from({ length: 24 }, (_, i) => {
                    const hourTemp = baseTemp + Math.sin((i - 12) * Math.PI / 12) * 4;
                    const hourCondition = i >= 6 && i <= 18 ? randomCondition : { code: 1009, text: '阴' };
                    return {
                      time: new Date(new Date().setHours(i)).toISOString(),
                      temp_c: Math.round(hourTemp),
                      temp_f: Math.round(hourTemp * 9 / 5 + 32),
                      condition: hourCondition,
                      chance_of_rain: i >= 14 && i <= 18 ? Math.floor(Math.random() * 80) : Math.floor(Math.random() * 20)
                    };
                  })
                },
                // 未来4天的预报
                ...Array.from({ length: 4 }, (_, i) => {
                  const date = new Date();
                  date.setDate(date.getDate() + i + 1);
                  const dayTemp = baseTemp + (Math.random() * 6 - 3);
                  const dayCondition = conditions[Math.floor(Math.random() * conditions.length)];
                  return {
                    date: date.toISOString().split('T')[0],
                    day: {
                      maxtemp_c: Math.round(dayTemp + 3),
                      mintemp_c: Math.round(dayTemp - 3),
                      condition: dayCondition,
                      daily_chance_of_rain: Math.floor(Math.random() * 60)
                    }
                  };
                })
              ]
            }
          };
        }
      },
      mounted() {
        // 初始化深色模式
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
          this.isDarkMode = true;
          document.documentElement.classList.add('dark');
        }
        
        // 加载最近搜索
        const savedSearches = localStorage.getItem('weatherAppRecentSearches');
        if (savedSearches) {
          this.recentSearches = JSON.parse(savedSearches);
        }
        
        // 初始加载北京的天气
        this.fetchWeatherData('北京市');
        
        // 每小时自动刷新
        setInterval(() => {
          this.now = new Date();
          if (this.now.getMinutes() === 0) {
            this.refreshWeather();
          }
        }, 60000);
      },
      watch: {
        // 监听最近搜索变化，保存到localStorage
        recentSearches: {
          handler(newVal) {
            localStorage.setItem('weatherAppRecentSearches', JSON.stringify(newVal));
          },
          deep: true
        }
      }
    });

    app.mount('#app');
  </script>
</body>
</html>  